<?php
class LRApi_account
{
	var $call = "";
	var $checkAccount = "";

	function LRApiAccount ($lrAccount, $apiName, $secretWord, $checkAccount)
	{
		$this->call = new LRApi ($lrAccount, $apiName, $secretWord);
		$this->checkAccount = $checkAccount;
	}

	function execute()
	{
		$authXml = $this->call->AuthXml();

		$xml = '<AccountNameRequest id="' . $this->call->id . '">' . $authXml .
					'<AccountName>' .
						'<AccountId>' . $this->call->lrAccount . '</AccountId>' .
						'<AccountToRetrieve>' . $this->checkAccount . '</AccountToRetrieve>' .
					'</AccountName>' .
				'</AccountNameRequest>';

		$response = $this->call->getResponse("https://api.libertyreserve.com/xml/accountname.aspx?req=", $xml);

		if ($response != "")
		return $this->parseResponse ($response);
		else return "";
	}

	function parseResponse ($responseXml)
	{
		$response = array();

		$doc = new DOMDocument();
		if (!$doc->loadXML($responseXml))
		{
			$error = "Can't parse server's XML response.";
			return $response;
		}

		$rootElem = $doc->getElementsByTagName("AccountNameResponse")->item(0);
		$responseId = $rootElem->getAttribute("id");

		if ($responseId != $this->call->id)
		{
			$error = "ResponseId does not match RequestId.";
			return $response;
		}

		$counter = 0;

		$childElems = $rootElem->getElementsByTagName("*");
		$elem = $childElems->item(0); // Should only be one element anyway

		if ($elem->tagName == "AccountName")
		{
			$acct = array ("AccountToRetrieve" => trim($elem->getElementsByTagName("AccountToRetrieve")->item(0)->textContent),
					"Date" => trim($elem->getElementsByTagName("Date")->item(0)->textContent),
					"Name" => trim($elem->getElementsByTagName("Name")->item(0)->textContent));

			$response = $acct;
		}
		else if ($elem->tagName == "Error")
		{
			$error = array ("ErrorCode" => trim($elem->getElementsByTagName("Code")->item(0)->textContent),
					"ErrorText" => trim($elem->getElementsByTagName("Text")->item(0)->textContent));

			$response = $error;
		}

		return $response;
	}
}
